<template>
  <div class="container">

    <!--头部操作-->
    <div class="header-box">
      <div class="left">
        <el-button type="primary" size="small" icon="el-icon-arrow-left" plain @click="goBack">返回</el-button>
      </div>
      <div class="right">
        <!--<el-button type="primary" size="small" @click="handleSubmitClick" :disabled="editable">提交</el-button>-->
        <el-button type="primary" size="small" @click="handleSubmitClick" v-if="!editable">提交</el-button>
        <el-button type="primary" size="small" v-if="taskDistributeBtnStatus" @click="taskDistributeStatus=true">任务分配</el-button>
      </div>
    </div>
    <!--头部操作-->

    <!--基本信息-->
    <card title="基本信息">
      <div class="context-warp">
        <div class="page-form-item" style="width:33.33%">
          <label class="page-form-item-label">
            <span class="page-form-item-label__text"><i class="icon" style="margin-right: 4px;">*</i>项目名称</span>
          </label>
          <div class="page-form-item-content">
            <zb-form-select-data v-bind="option" v-model="baseData.projectName" :disabled="editable" @dataChange></zb-form-select-data>
          </div>
        </div>

        <div class="page-form-item" style="width:33.33%">
          <label class="page-form-item-label">
            <span class="page-form-item-label__text">流程标题</span>
          </label>
          <div class="page-form-item-content">
            {{baseData.projectName+'竣工验收'+baseData.createTime}}
          </div>
        </div>

        <div class="page-form-item" style="width:33.33%">
          <label class="page-form-item-label">
            <span class="page-form-item-label__text"><i class="icon" style="margin-right: 4px;">*</i>合同名称</span>
          </label>
          <div class="page-form-item-content">
            <el-select v-model="baseData.contractTitle" :disabled="editable" clearable filterable @change="handleContractChange">
              <el-option :label="item.contractTitle" :value="item.id" :key="item.id" v-for="item in contractList"></el-option>
            </el-select>
          </div>
        </div>

        <div class="page-form-item" style="width:33.33%" v-if="type!=='add'">
          <label class="page-form-item-label">
            <span class="page-form-item-label__text">提交人</span>
          </label>
          <div class="page-form-item-content">
            <el-input v-model.trim="baseData.createName" disabled></el-input>
          </div>
        </div>

        <div class="page-form-item" style="width:33.33%" v-if="type!=='add'">
          <label class="page-form-item-label">
            <span class="page-form-item-label__text">提交时间</span>
          </label>
          <div class="page-form-item-content">
            <el-date-picker v-model="baseData.createTime" type="date" disabled placeholder="选择日期"></el-date-picker>
          </div>
        </div>


        <div class="page-form-item" style="width:33.33%" v-if="type!=='add'">
          <label class="page-form-item-label">
            <span class="page-form-item-label__text"></span>
          </label>
          <div class="page-form-item-content">
          </div>
        </div>
      </div>
    </card>
    <!--基本信息-->

    <!--合同列表-->
    <card title="附件">
      <el-table ref="elTable" :data="list" size="small" stripe min-height="400" max-height="500" border>
        <el-table-column type="index" label="序号" width="55"></el-table-column>
        <el-table-column prop="title" label="资料类型" width="200"></el-table-column>
        <el-table-column prop="fileInfos" label="资料名称">
          <template slot-scope="scope">
            <div style="display: flex">
              <file-upload :fileList="scope.row.fileInfos" :disabled="editable"
                           @handleUploadSuccess="(file) => handleUploadSuccess(file,scope.$index)"
                           @handleFileRemove="(file) => handleFileRemove(file,scope.$index)"></file-upload>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createBy" label="上传人" width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="createTime" label="上传时间" width="200" show-overflow-tooltip></el-table-column>
      </el-table>
    </card>
    <!--合同列表-->


    <!--技改需求明细表-->
    <card title="技改需求明细表">
      <el-table :data="pigfarmProjectDemandList" border>
        <el-table-column label="场区" prop="deptName" :show-overflow-tooltip="true" >
          <template slot-scope="scope">
            <el-select size="small" style="width:100%" v-model="scope.row.areaDictId" disabled placeholder="请选择">
              <el-option
                v-for="item in areaList"
                :key="item.value"
                :label="item.value"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="单体" prop="deptName" :show-overflow-tooltip="true" >
          <template slot-scope="scope">
            <el-input size="small" v-model="scope.row.nodeName" disabled maxlength="30" placeholder="请输入内容"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="改造需求" prop="deptName" :show-overflow-tooltip="true" >
          <template slot-scope="scope">
            <el-input size="small" v-model="scope.row.remark" disabled maxlength="30" placeholder="请输入内容"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="改造前照片" prop="deptName" :show-overflow-tooltip="true" >
          <template slot-scope="scope">
            <fileUpload v-model='scope.row.fileList1' :limit="3" disabled />
          </template>
        </el-table-column>

        <el-table-column label="改造后照片" prop="deptName" :show-overflow-tooltip="true" >
          <template slot-scope="scope">
            <fileUpload v-model='scope.row.fileList2' :limit="3" :disabled="editable" />
          </template>
        </el-table-column>

      </el-table>
    </card>
    <!--技改需求明细表-->

    <!--任务分配窗口模块-->
    <el-dialog title="任务分配" :visible.sync="taskDistributeStatus" width="400px">
      <el-form :model="taskDistributeForm" label-width="80px">
        <el-form-item label="设计人员">
          <zb-form-select-data v-bind="dutyOptions" v-model="taskDistributeForm.dealName" @dataChange="handleDesignLeaderChange"></zb-form-select-data>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="taskDistributeStatus = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirmClick">确 定</el-button>
      </div>
    </el-dialog>
    <!--任务分配窗口模块-->


  </div>
</template>

<script>
  import { getDetailInfoApi, getContractListApi, addAndUpdateApi ,getDictList ,getDemandList, getTaskDistributeBtnById, setTaskDistributeApi } from '@/api/acceptanceManage/completeAcceptance'
  import card from "@/components/Card/index";
  import fileUpload from '@/views/components/fileUpload/index.vue'
  import { getCurrentDate } from "@/utils/dateUtils";
  import { newWindowBpm } from "@/utils/openBpm";
  // import FileUpload from '@/views/components/fileUpload/index.vue'
  import Index from "./index";
  import {getToken} from "@/utils/auth";
  import BaseIndex from "@/views/base/BaseIndex";
  import store from "@/store";
  import router from "@/router";
  export default {
    name: "completeAcceptanceDetail",
    components:{ card, fileUpload },
    extends:BaseIndex,
    data(){
      return {
        editable:false,//是否可编辑
        type:"add",//
        option:{
          label: "项目名称",
          prop: "projectName",
          type: "selectData",
          searchKey: "projectName",
          span: 8,
          url: `${process.env.VUE_APP_BASE_API}/pigfarm-project/like?progress=100`,
          props: {
            label: "projectName",
            value: "projectId"
          },
          createdRequest: false,
          searchIconVisible:true,
          filterAble:false,
          selectAble: true,
          getDictSuccessStatus:0,
          getDictResultMap:{
            status:'data.code',
            data:'data.data',
            list:'data.data.records',
            total:'data.data.total',
          },
          dialogType:2,
          labelFields:['pigfarmName','pigfarmNumber','projectName','projectNumber'],
          labelFieldsName:['猪场名称','猪场编号','项目名称','项目编号'],
          searchLabel:['projectName'],
          searchLabelName:['项目名称'],
          headers:{
            Authorization:'Bearer '+getToken()
          },
          listeners: {
            dataChange: val => {
              if (val){
                const { projectId,projectName, projectNumber } = val;
                //debugger
                this.baseData.projectId = projectId;
                this.baseData.projectName = projectName;
                this.baseData.projectNumber = projectNumber;
                this.baseData.contractId = "";//重置合同
                this.baseData.contractTitle = "";//重置合同
                this.getContractList(projectId,this.baseData.contractTitle);

                getDemandList(projectId).then(
                  response => {
                    if(response && response.code ===0){

                      this.pigfarmProjectDemandList = response.data
                    }else{
                      this.msgError(response.msg)
                    }
                  }
                );

              }
            }
          }
        },
        baseData:{
          projectId: "",
          projectName: "",
          projectNumber: "",
          contractId:'',
          contractTitle:'',
          createName:this.$store.getters.account,
          createTime:getCurrentDate(),
          meetingFiles:[],//竣工验收会议纪要
          videoFiles:[],//影像资料
          checkFiles:[],//验收报告
          reformFiles:[],//整改报告
          otherFiles:[],//其他报告
        },
        //表格数据
        list: [
          {id:4,title:'竣工验收会议纪要',fileInfos:[],createBy:'',createTime:''},
          {id:1,title:'验收报告',fileInfos:[],createBy:'',createTime:''},
          {id:2,title:'整改报告',fileInfos:[],createBy:'',createTime:''},
          {id:5,title:'影像资料',fileInfos:[],createBy:'',createTime:''},
          {id:3,title:'其他报告',fileInfos:[],createBy:'',createTime:''},
        ],
        contractList:[],//合同列表
        areaList:[],
        pigfarmProjectDemandList:[],


        taskDistributeBtnStatus:true,//是否显示任务分配按钮(审批完成状态 &&(当前登录人=设计组长 || 调用/design-info/complete接口返回true))
        taskDistributeStatus:false,//任务分配窗口显隐状态
        taskDistributeForm:{ dealOa:"", dealName:"" },//任务分配窗口表单
        //系统用户配置
        dutyOptions: {
          label: "责任人",
          prop: "nameCn",
          type: "selectData",
          searchKey: "nameCn",
          span: 12,
          url: `${process.env.VUE_APP_BASE_API}/common/list`,
          props: {
            label: "nameCn",
            value: "account"
          },
          height: 62,
          createdRequest: false,
          searchIconVisible: true,
          filterAble: false,
          getDictSuccessStatus: 0,
          getDictResultMap: {
            status: 'data.code',
            data: 'data.data',
            list: 'data.data.records',
            total: 'data.data.total',
          },
          method: 'post',
          dialogType: 2,
          labelFields: ['nameCn', 'account', 'deptName'],
          labelFieldsName: ['用户名', '账户', '所属部门'],
          searchLabel: ['nameCn'],
          searchLabelName: ['用户名'],
          headers: {
            Authorization: 'Bearer ' + getToken()
          },
        },

      }
    },
    activated(){
      if (
        (this.$route.query.type && this.$route.query.type!=='add')
        || this.$route.query.id
      ){
        this.$store.dispatch('tagsView/delCachedView', this.$route)
      }
    },
    created(){
      const { type, id } = this.$route.query;
      this.editable = type === 'view';
      this.type = type;
      if(type==="add"){
        this.taskDistributeBtnStatus = false;
      }

      if(id){
        this.getDetailInfo(id);
      }

      getDictList().then(
        response => {
          if(response && response.code ===0){
            this.areaList = response.data
          }else{
            this.msgError(response.msg)
          }
          this.loading = false;
        }
      );
    },


    methods:{

      /**
       *获取任务分配按钮权限
       */
      getTaskDistributeBtnPermission(){
        const { projectId, contractId } = this.baseData;
        getTaskDistributeBtnById(projectId,contractId).then(res => {
          //debugger
          if(res.code === 0){
            const { status, budgetLeader } = this.form;
            console.log("getters:",this.$store.getters);
            const { account } = this.$store.getters;
            if(status==="completed" && !res.data && (budgetLeader===account || account==='admin')  ){
              this.taskDistributeBtnStatus = true;
            }else{
              this.taskDistributeBtnStatus = false;
            }
          }else{
            this.$message.error(res.msg);
          }
        }).catch(error => {
          console.log(error);
        })
      },


      /**
       * 获取详情
       */
      getDetailInfo(id){
        const loading = this.$loading({lock: true, text: 'Loading', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)'});
        getDetailInfoApi(id).then(res => {
          console.log('详情:',res);
          loading.close();
          if(res.code === 0){

            this.pigfarmProjectDemandList = res.data.pigfarmProjectDemandList
            // debugger
            this.baseData = res.data;
            let { status, meetingFiles,checkFiles, reformFiles,videoFiles,  otherFiles} = res.data;
            this.$set(this.list[0],'fileInfos',meetingFiles);
            this.$set(this.list[0],'createBy',meetingFiles[0]?.createBy);
            this.$set(this.list[0],'createTime',meetingFiles[0]?.createTime);
            this.$set(this.list[1],'fileInfos',checkFiles);
            this.$set(this.list[1],'createBy',checkFiles[0]?.createBy);
            this.$set(this.list[1],'createTime',checkFiles[0]?.createTime);
            this.$set(this.list[2],'fileInfos',reformFiles);
            this.$set(this.list[2],'createBy',reformFiles[0]?.createBy);
            this.$set(this.list[2],'createTime',reformFiles[0]?.createTime);
            this.$set(this.list[3],'fileInfos',videoFiles);
            this.$set(this.list[3],'createBy',videoFiles[0]?.createBy);
            this.$set(this.list[3],'createTime',videoFiles[0]?.createTime);
            this.$set(this.list[4],'fileInfos',otherFiles);
            this.$set(this.list[4],'createBy',otherFiles[0]?.createBy);
            this.$set(this.list[4],'createTime',otherFiles[0]?.createTime);
            if(this.$route.query.type==="view"){
              this.editable = true;
            }else{
              //设置编辑状态(暂存 || 退回、驳回 ||作废状态可编辑)
              if(!status || status === 'save' || status === 'reject' || status === 'cancel'){
                this.editable = false;
              }else{
                this.editable = true;
              }
            }
            this.getTaskDistributeBtnPermission();//获取任务分配按钮权限
          }else{
            this.$message.warning(res.msg);
          }
        }).catch(error => {
          console.log('error:',error);
          loading.close();
        })
      },

      /**
       * 获取合同列表
       */
      getContractList(projectId,contractTitle){
        const loading = this.$loading({lock: true, text: 'Loading', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)'});
        getContractListApi(projectId,contractTitle).then(res => {
          console.log('合同列表:',res);
          loading.close();
          if(res.code === 0){
            this.contractList = res.data;
          }else{
            this.$message.warning(res.msg);
          }
        }).catch(error => {
          console.log('error:',error);
          loading.close();
        })
      },

      /**
       * 数据校验
       */
      checkData(){
        const { projectName, contractTitle } = this.baseData;
        //debugger
        if(!projectName){
          this.$message.warning("请选择项目!");
          return false;
        }else if(!contractTitle){
          this.$message.warning("请选择合同!");
          return false;
        }else{
          if(!this.list[0].fileInfos.length){
            this.$message.warning("请上传 竣工验收会议纪要!");
            return false;
          }else if(!this.list[1].fileInfos.length){
            this.$message.warning("请上传 验收报告附件!");
            return false;
          }else if(!this.list[2].fileInfos.length){
            this.$message.warning("请上传 整改报告附件!");
            return false;
          }else if(!this.list[3].fileInfos.length){
            this.$message.warning("请上传 影像资料附件!");
            return false;
          }else if(!this.list[4].fileInfos.length){
            this.$message.warning("请上传 其他报告附件!");
            return false;
          }else{
            return true
          }
        }
      },



      /**
       * 提交
       */
      handleSubmitClick(){
        const status = this.checkData();
        if(status){
          const { type } = this.$route.query;
          console.log('baseData:',this.baseData);
          //组装附件数据
          this.baseData.meetingFiles = this.list[0].fileInfos;
          this.baseData.checkFiles = this.list[1].fileInfos;
          this.baseData.reformFiles = this.list[2].fileInfos;
          this.baseData.videoFiles = this.list[3].fileInfos;
          this.baseData.otherFiles = this.list[4].fileInfos;// 新增的附件

          this.baseData['pigfarmProjectDemandList'] = this.pigfarmProjectDemandList
          //去除提交人和提交时间(接口不需要)
          delete this.baseData.createTime;
          delete this.baseData.createName;
          const loading = this.$loading({lock: true, text: 'Loading', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)'});
          addAndUpdateApi(type,this.baseData).then(res => {
            console.log('新增:',res);
            loading.close();
            if(res.code === 0){
              this.$message.success("提交成功");
              newWindowBpm(res.data,true,{path:`/completeAcceptance/index`},true, Index);
              this.$store.dispatch('tagsView/delCachedView', Index)
                .then(() => {
                  this.$router.push({
                    path:'/acceptanceManage/completeAcceptance'
                  })
                })

            }else{
              this.$message.warning(res.msg);
            }
          }).catch(error => {
            console.log('error:',error);
            loading.close();
          })
        }
      },


      /**
       * 合同change事件
       */
      handleContractChange(val){
        const obj = this.contractList.find(item => {
          return item.id === val;
        });
        //debugger
        const { contractTitle } = obj;
        this.baseData.contractId = val;
        this.baseData.contractTitle = contractTitle;
      },


      /**
       *文件上传成功
       * @param files
       * @param index
       */
      handleUploadSuccess(files,index){
        // debugger
        this.list[index].fileInfos = files;
        if(files.length){
          const { createBy, createTime } = files[files.length-1];//获取最新上传信息
          this.$set(this.list[index],'createBy',createBy);
          this.$set(this.list[index],'createTime',createTime);
        }
      },

      /**
       *文件删除
       * @param files
       * @param index
       */
      handleFileRemove(files,index){
        //debugger
        this.list[index].fileInfos = files;
      },

      /**
       *二次设计组长选择事件
       * @param val
       */
      handleDesignLeaderChange(val){
        console.log(val);
        const { account, nameCn } = val;
        //debugger
        this.taskDistributeForm.dealOa = account;
        this.taskDistributeForm.dealName = nameCn;
      },

      /**
       * 分配任务窗口确认事件
       */
      handleConfirmClick() {
        const { dealOa, dealName } = this.taskDistributeForm;
        const { projectId, contractId } = this.baseData;
        if(!dealOa){
          this.$message.warning("请选择设计人员");
        }else{
          const loading = this.$loading({lock: true, text: 'Loading', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)'});
          //debugger;
          setTaskDistributeApi(projectId,contractId,dealOa,dealName).then(res => {
            loading.close();
            if(res.code===0){
              this.$message.success("分配成功");
              this.taskDistributeStatus = false;
            }else{
              this.$message.error(res.msg);
            }
          }).catch(err => {
            console.log(err);
            loading.close();
          })
        }
      },
    }
  }
</script>

<style scoped lang="scss">
  @import "../../../style/form"; //table样式
  .container {
    .header-box{
      display: flex;
      width: 100%;
      height: 60px;
      line-height: 60px;
      padding: 20px;
      box-sizing: border-box;
      .left{
        display: flex;
        justify-content: flex-start;
        align-items: center;
        width: 20%;
      }
      .right{
        display: flex;
        justify-content: flex-end;
        align-items: center;
        width: 80%;
      }
    }
    .tool-box{
      display: flex;
      justify-content: flex-end;
      align-items: center;
      margin-bottom: 5px;
    }
  }
</style>
